package com.wzq.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.dao.pojo.*;
import com.wzq.service.IRecommendService;
import com.wzq.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/recommend")
public class AdminRecommendController extends GetSome{

    @Autowired
    IRecommendService iRecommendService;
    @RequestMapping("/list")        //添加
    public R list(@RequestBody PageBean pageBean) {
        String query=pageBean.getQuery().trim();
        Wechat_user wechat_user = new Wechat_user();
        Page<Recommend> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        Page<Recommend> pageResult = iRecommendService.page(page, new QueryWrapper<Recommend>().in(StringUtil.isNotEmpty(query),"p_id", searchByPname(query)));
        Map<String,Object> map=new HashMap<>();
        //        添加用户名称和项目名称
        List<Recommend> recommendes=new ArrayList<>();
        for (Recommend recommend : pageResult.getRecords()) {
            recommend.setP_name( getP_name(recommend.getP_id()) );
            recommendes.add(recommend);
        }
        map.put("RecommendList",pageResult.getRecords());
        map.put("total",pageResult.getTotal());
        return R.ok(map);
    }

    @RequestMapping("/save")        //添加修改
    public R save(@RequestBody Recommend recommend){
        if(recommend.getId()==null || recommend.getId()==-1){
            Sum sum = iSumService.getById(1);
            boolean flag= sum.getSum().intValue() >= iRecommendService.count() + 1 ? true : false;
            if(flag) {
                iRecommendService.save(recommend);
            }
            else
            {
            return   R.error(500,"超出了");
            }
        }else{
            iRecommendService.saveOrUpdate(recommend);
        }
        return R.ok();
    }



    @GetMapping("/{id}")            //单个回显
    public R findById(@PathVariable(value = "id")Integer id){
        Recommend recommend = iRecommendService.getById(id);
        //        获得用户名称和项目名称
        recommend.setP_name( getP_name(recommend.getP_id()) );
        Map<String,Object> map=new HashMap<>();
        map.put("recommend",recommend);
        return R.ok(map);
    }

    @GetMapping("/delete/{id}")     //删除
    public R delete(@PathVariable(value = "id")Integer id){
        iRecommendService.removeById(id);
        return R.ok();
    }
}
